using System.Text;
using Android.App;
using Android.GoogleMaps;
using Android.Graphics.Drawables;
using Android.Locations;
using Android.OS;
using Android.Widget;
using Android.Graphics;
using System.Linq;


namespace MuseumsBC.Activities
{
    [Activity(Label = "Near Me Map")]
    public class NearMeMapActivity : MapActivity, ILocationListener
    {
        //private GeoPoint MuseumLocation
        //{
        //    get
        //    {
        //        int latE6 = (int)(_Museum.Latitude * 1e6);
        //        int lonE6 = (int)(_Museum.Longitude * 1e6);
        //        return new GeoPoint(latE6, lonE6);
        //    }
        //}

        private TextView _locationText;
        private LocationManager _locationManager;
        private StringBuilder _builder;
        private Geocoder _geocoder;

        private GeoPoint UserLocation { get; set; }

        private MapView mapView { get; set; }
        MyItemizedOverlay myItemizedOverlay;

        private Drawable Marker;

        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);

            SetContentView(Resource.Layout.NearMeMap);

            mapView = FindViewById<MapView>(Resource.NearMeMap.Map);
            mapView.Controller.SetZoom(10);

            Marker = Resources.GetDrawable(Resource.Drawable.MapMarker); //these are the markers put on the map
            Marker.Bounds = new Rect(0, 0, 48, 33); // without bounds, marker doesn't appear (?)

            myItemizedOverlay = new MyItemizedOverlay(this, Marker);
            mapView.Overlays.Add(myItemizedOverlay);
            mapView.PostInvalidate();

            //Drawable marker = Resources.GetDrawable(Resource.Drawable.Icon); //these are the markers put on the map
            //myItemizedOverlay = new MyItemizedOverlay(this, marker);
            //mapView.Overlays.Add(myItemizedOverlay);
            //mapView.PostInvalidate();


            _builder = new StringBuilder();
            _geocoder = new Geocoder(this);
            _locationText = FindViewById<TextView>(Resource.NearMeMap.location_text);
            _locationManager = (LocationManager)GetSystemService(LocationService);

            var criteria = new Criteria() { Accuracy = Accuracy.NoRequirement };
            string bestProvider = _locationManager.GetBestProvider(criteria, true);

            Location lastKnownLocation = _locationManager.GetLastKnownLocation(bestProvider);


            if (lastKnownLocation != null)
            {
                var point = new GeoPoint((int)(lastKnownLocation.Latitude * 1e6), (int)(lastKnownLocation.Longitude * 1e6));

                mapView.Controller.AnimateTo(point);

                var overlayItem = new OverlayItem(point, "DTU", "Anker Engelunds Vej 101");
                //Marker.Bounds = new Rect(0, 0, 48, 33);
                overlayItem.SetMarker(Marker);
                //TODO: exception below
                myItemizedOverlay.AddOverlayItem(overlayItem);

                _locationText.Text = string.Format("Last known location, lat: {0}, long: {1}",
                                                   lastKnownLocation.Latitude, lastKnownLocation.Longitude);
            }

            _locationManager.RequestLocationUpdates(bestProvider, 5000, 2, this);




            //var mapView = FindViewById<MapView>(Resource.MuseumDetailMap.Map);
            ////mapView.Controller.AnimateTo(MuseumLocation);
            //mapView.Controller.SetZoom(10);
        }

        #region ILocationListener Members

        public void OnLocationChanged(Location location)
        {
            // remove old overlay item from itemizedoverlay
            //int x;
            //if (myItemizedOverlay.OverlayItems.Select(o => o.Point == UserLocation).Any())
            //    x = 10;
            //var i = myItemizedOverlay.OverlayItems.Select(o => o.Point == UserLocation);

            var point = new GeoPoint((int)(location.Latitude * 1e6), (int)(location.Longitude * 1e6));
            mapView.Controller.AnimateTo(point);
            UserLocation = point;

            var overlayItem = new OverlayItem(point, "DTU", "Anker Engelunds Vej 101");
            //Marker.Bounds = new Rect(0, 0, 48, 33);
            overlayItem.SetMarker(Marker);
            myItemizedOverlay.AddOverlayItem(overlayItem);


            _builder.AppendLine(
                            string.Format("Location updated, lat: {0}, long: {1}",
                                          location.Latitude, location.Longitude)
                        );

            //try
            //{
            //    Address address =
            //        _geocoder
            //            .GetFromLocation(location.Latitude, location.Longitude, 1)
            //            .FirstOrDefault();

            //    if (address != null)
            //    {
            //        _builder.AppendLine(" -> " + address.CountryName);
            //    }
            //}
            //catch (IOException io)
            //{
            //    Android.Util.Log.Debug("LocationActivity", io.Message);
            //}

            _locationText.Text = _builder.ToString();
        }

        public void OnProviderDisabled(string provider)
        {
        }

        public void OnProviderEnabled(string provider)
        {
        }

        public void OnStatusChanged(string provider, Availability status, Bundle extras)
        {
        }

        #endregion

        protected override bool IsRouteDisplayed
        {
            get { return false; }
        }
    }
}